package com.example.his.api.mis.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaMode;
import cn.hutool.core.bean.BeanUtil;
import com.example.his.api.common.PageUtils;
import com.example.his.api.common.R;
import com.example.his.api.db.dao.RuleDao;
import com.example.his.api.db.pojo.RuleEntiy;
import com.example.his.api.mis.controller.form.rule.*;
import com.example.his.api.mis.service.RuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/mis/rule")
public class RuleController {
  
  @Resource
  private RuleService ruleService;
  @Autowired
  private RuleDao ruleDao;
  
  @GetMapping("/searchAllRule")
  @SaCheckLogin
  public R searchAllRule() {
    ArrayList <HashMap> list = ruleService.searchAllRule();
    return R.ok().put("result", list);
  }
  
  @PostMapping("/searchByPage")
  @SaCheckPermission(value = { "ROOT", "RULE:SELECT" }, mode = SaMode.OR)
  public R searchByPage(@RequestBody @Valid SearchRuleByPageForm form) {
    int page = form.getPage();
    int length = form.getLength();
    int start = (page - 1) * length;
    Map param = BeanUtil.beanToMap(form);
    param.put("start", start);
    PageUtils pageUtils = ruleService.searchByPage(param);
    return R.ok().put("result", pageUtils);
  }
  
  @PostMapping("/insert")
  @SaCheckPermission(value = { "ROOT", "RULE:INSERT" }, mode = SaMode.OR)
  public R insert(@RequestBody @Valid InsertRuleForm form) {
    RuleEntiy entity = BeanUtil.toBean(form, RuleEntiy.class);
    boolean bool = ruleService.insert(entity);
    return R.ok().put("result", bool);
  }
  
  @PostMapping("/searchById")
  @SaCheckPermission(value = { "ROOT", "RULE:SELECT" }, mode = SaMode.OR)
  public R searchById(@RequestBody @Valid SearchRuleByIdForm form) {
    HashMap map = ruleService.searchById(form.getId());
    return R.ok().put("result", map);
  }
  
  @PostMapping("/update")
  @SaCheckPermission(value = { "ROOT", "RULE:UPDATE" }, mode = SaMode.OR)
  public R update(@RequestBody @Valid UpdateRuleForm form) {
    RuleEntiy entity = BeanUtil.toBean(form, RuleEntiy.class);
    boolean bool = ruleService.update(entity);
    return R.ok().put("result", bool);
  }
  
  @PostMapping("/deleteById")
  @SaCheckPermission(value = { "ROOT", "RULE:DELETE" }, mode = SaMode.OR)
  public R deleteById(@RequestBody @Valid DeleteRuleByIdForm form) {
    boolean bool = ruleService.deleteById(form.getId());
    
    return R.ok().put("result", bool);
    
  }
  
  
}
